/*
 * @Author: luoqi
 * @Date: 2022-04-17 21:39:22
 * @LastEditors: luoqi
 * @LastEditTime: 2022-05-05 15:14:52
 * @Description: 
 */
import Vue from 'vue'
import Vuex from 'vuex'
import home from './home'
import exp from './exp'
import utils from '../utils/utils'
import axios from '../utils/axios';
import { Message } from "element-ui";
import qs from 'qs'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    classifyTree: utils.getStorage('ClassifyTree') || {},
    herData: {},//他人收藏信息
    mySelect: {},//我的收藏信息
    isLogin: utils.getStorage('isLogin'),
    noti: null,//消息列表
    newChat: {},//新消息
    sideList:[],//联系人列表
  },
  mutations: {
    setClassifyTree(state, classifyTree) {
      state.classifyTree = classifyTree
    },
    setHerData(state, obj) {
      state.herData = obj
    },
    setMySelect(state, obj) {
      state.mySelect = obj
    },
    changeLog(state, status) {
      state.isLogin = status
    },
    //修改联系人数组
    setList(state, obj) {
      state.sideList = obj
    },
    //初始化联系人数组
    setNoti(state, obj) {
      //创建联系人数组
      let notiObj = obj.chatNotify;
      let arr = [];
      for (let key in notiObj) {
        if(notiObj[key].messageVos.length>0){
          let obj = {};
        obj.receiverId = parseInt(key);
        let msgArr = notiObj[key].messageVos
        for (let i = 0; i < msgArr.length; i++) {
          //对方发出的信息
          if (msgArr[i].createId != utils.getStorage('userinfo').id) {
            obj.headImg = msgArr[i].createHeadImg;
            obj.nickname = msgArr[i].createName;
            break;
          }else{
            obj.headImg = msgArr[i].receiverHeadImg;
            obj.nickname = msgArr[i].receiverName;
            break;
          }
        }
        obj.unReadNum = notiObj[key].unReadNum;
        obj.createTime = notiObj[key].messageVos[0].createTime;
        obj.msg = notiObj[key].messageVos[0].content;
        arr.push(obj);
        }
        
      }
      state.sideList = arr;
      //存储消息信息
      state.noti = obj
    },
    //新消息
    setChat(state, obj) {
      console.log(obj)
      //发出用户已经存在于联系人数组
      if(state.sideList.find(item=>{return item.receiverId==obj.createId})){
        console.log("收到新消息，该用户存在于联系人列表")
        //修改时间、msg内容、未读消息数量
        console.log(state.sideList)
        let newList=state.sideList.map(item=>{
          if(item.receiverId==obj.createId){
            item.createTime = obj.createTime;
            item.msg = obj.content;
            item.unReadNum =item.unReadNum+1;
          }
          return item
        })
        state.sideList=newList
      }else{
        console.log("收到新消息，该用户没有存在于联系人列表")
        state.sideList.unshift({...obj,headImg:obj.createHeadImg,nickname:obj.createName,unReadNum:1,msg:obj.content})
      }
      state.newChat = obj
    }
  },
  actions: {
    getClassifyTree(obj) {
      // 在这里发起ajax请求 
      return new Promise((resolve, reject) => {
        axios({
          method: 'get',
          url: '/classify/getClassifyTree',
        })
          .then((res) => {
            console.log(res)
            if (res.code == 200) {
              let classifyTree = res.data
              // obj.commit('mutation里的函数名')
              obj.commit('setClassifyTree', classifyTree)
              // sessionStorage 浏览器的本地储存
              utils.setStorage('classifyTree', classifyTree)
              resolve(1)
            } else {
              Message({
                message: '哎呀网络出错了，请刷新页面试试！',
                type: 'error'
              });
            }
          })
          .catch((err) => {
            console.log(err);
          })
      })
    },
    //收藏
    collection(context, data) {
      let { targetId, status, type } = data
      if (utils.getStorage('userinfo')) {
        return new Promise(function (resolve, reject) {
          axios({
            method: 'post',
            url: '/collection/addOrCancel',
            data: qs.stringify({
              status: status,
              type: type,
              targetId: targetId,
              userId: utils.getStorage('userinfo').id
            })
          })
            .then((res) => {
              console.log(res)
              if (res.code == 200) {
                resolve(res)
              } else {
                Message({
                  message: '哎呀网络出错了，请刷新页面试试！',
                  type: 'error'
                });
              }
            })
            .catch((err) => {
              console.log(err);
            })
        })
      } else {
        window.location.href = '/main/login'
      }

    },
    //获取他人信息并存储
    getHerData(context, id) {
      return new Promise((resolve, reject) => {
        axios({
          url: "/user/findById",
          method: "post",
          data: qs.stringify({
            userId: id,
          })
        }).then((res) => {
          console.log(res)
          if (res.code == 200) {
            let obj = { data: res.data, detail: res.detail, collection: res.collection, isConcern: res.isConcern }
            context.commit('setHerData', obj)
            resolve(obj)
          } else {
            Message({
              message: '哎呀网络出错了，请刷新页面试试！',
              type: 'error'
            });
          }
        })
          .catch((err) => {
            console.log(err);
          })
      })
    },
    //获取个人收藏信息并存储
    getMySelect(context) {
      return new Promise((resolve, reject) => {
        axios({
          url: '/collection/selectHistory',
          method: 'post',
          data: qs.stringify({
            userId: utils.getStorage("userinfo").id,
          })
        })
          .then((res) => {
            console.log(res)
            if (res.code == 200) {
              context.commit('setMySelect', res.data)
              resolve(res.data)
            } else {
              Message({
                message: '哎呀网络出错了，请刷新页面试试！',
                type: 'error'
              });
            }
          })
          .catch((err) => {
            console.log(err);
          })
      })
    }
  },
  modules: {
    home: home,
    exp: exp
  }
})
